package com.xvaca.spcms.servlet.admin.pipe;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xvaca.spcms.bean.PipeBean;
import com.xvaca.spcms.cache.Cache;
import com.xvaca.spcms.dao.ChannelDAO;
import com.xvaca.spcms.dao.PartnerDAO;
import com.xvaca.spcms.dao.PipeDAO;

/**
 * Servlet implementation class PipeAddServlet
 */
public class PipeAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		ChannelDAO channelDao = new ChannelDAO();
		PartnerDAO partnerDao = new PartnerDAO();
		
		request.setAttribute("channels", channelDao.getChannelList());
		request.setAttribute("partners", partnerDao.getPartnerList());
		
		request.getRequestDispatcher("pipe_add.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		String channelId = request.getParameter("channel_id");
		String name = request.getParameter("name");
		String cmd = request.getParameter("cmd");
		String partnerId = request.getParameter("partner_id");
		String syncUrl = request.getParameter("sync_url");
		String price = request.getParameter("price");
		String deduction = request.getParameter("deduction");
		String status = request.getParameter("status");
		String desc = request.getParameter("desc");
		String needMO = request.getParameter("need_mo");
		
		String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		
		PipeBean pipe = new PipeBean();
		pipe.setChannelId(Integer.parseInt(channelId));
		pipe.setCmd(cmd);
		pipe.setCreatedAt(currentTime);
		pipe.setDeduction(Double.parseDouble(deduction));
		pipe.setDescription(desc);
		pipe.setName(name);
		pipe.setPartnerId(Integer.parseInt(partnerId));
		pipe.setPrice(Integer.parseInt(price));
		pipe.setStatus(Integer.parseInt(status));
		pipe.setSyncUrl(syncUrl);
		pipe.setUpdatedAt(currentTime);
		pipe.setNeedMO(Integer.parseInt(needMO));
		
		PipeDAO dao = new PipeDAO();
		pipe = dao.insertPipe(pipe);
		
		// 更新缓存
		Cache.pipes.put(pipe.getId(), pipe);
		
		response.sendRedirect("pipeList");
		
	}

}
